package com.yhy;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * Created by yhy on 17-7-11.
 */
public class SpringContainerMain {
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringContainerMain.class);
    //spring 配置文件
    public static final String SPRING_CONFIG = "spring-application.xml";
    //找指定的XML配置文件，找到并装载完成ApplicationContext的实例化工作
    private static ClassPathXmlApplicationContext context=null;
    //等待结束信号
    private static Object waitTerm = new Object();

    /**
     * 获取spring应用上下文
     * @return
     */
    public static ClassPathXmlApplicationContext getContext() {
        return context;
    }

    /**
     * 启动 spring 容器
     */
    public void start() {
        context = new ClassPathXmlApplicationContext(SPRING_CONFIG);
        context.start();
    }

    /**
     * 关闭 spring 容器
     */
    public void stop() {
        try {
            if (context != null) {
                context.stop();
                context.close();
                context = null;
            }
        } catch (Throwable throwable) {
            LOGGER.error(throwable.toString(), throwable);
        }

    }


    ////////////////////////主函数////////////////////////////
    public static void main( String args[] ) {
        try{
            SpringContainerMain springContainer = new SpringContainerMain();
            springContainer.start();

            //==========开启子线程等待 SIGINT 和 SIGTERM 信号============
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        springContainer.stop();
                    } catch (Throwable var6) {
                    }
                    synchronized(waitTerm) {
                        waitTerm.notify();
                        LOGGER.info("===================thread {} recv sig  SIGINT/SIGTERM, notify main thread to stop===================", Thread.currentThread().getId());
                    }
                }
            });

            //==========主线程等待结束信号========================
            synchronized(waitTerm) {
                try {
                    waitTerm.wait();
                    LOGGER.info("=====================main thread {} recv sig to stop===============",Thread.currentThread().getId());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    LOGGER.error("{}",e.toString());
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("{}",e.toString());
        }
    }


}
